package com.example.shuimu;

import android.serialport.SerialPort;
import android.util.Log;

import com.serotonin.modbus4j.serial.SerialPortWrapper;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPortWrapperImpl implements SerialPortWrapper {
    private static final String TAG = "SerialPortWrapper";
    private SerialPort mSerialPort = null;
    private InputStream inputStream = null;
    private OutputStream outputStream = null;
    private String device;
    private int baudRate;
    private int dataBits;
    private int stopBits;
    private int parity;

    public SerialPortWrapperImpl(String device, int baudRate, int dataBits, int stopBits, int parity) {
        this.device = device;
        this.baudRate = baudRate;
        this.dataBits = dataBits;
        this.stopBits = stopBits;
        this.parity = parity;
    }

    @Override
    public void open() throws Exception{
        File fdevice = new File(device);
        if (!fdevice.canRead() || !fdevice.canWrite()) {
            Log.w(TAG, "File cant rw!");
        }
        try {
            mSerialPort = SerialPort // 串口对象
                    .newBuilder(fdevice, baudRate) // 串口地址地址，波特率
                    .dataBits(dataBits) // 数据位,默认8；可选值为5~8
                    .stopBits(stopBits) // 停止位，默认1；1:1位停止位；2:2位停止位
                    .parity(parity) // 校验位；0:无校验位(NONE，默认)；1:奇校验位(ODD);2:偶校验位(EVEN)
                    .build(); // 打开串口并返回
            if (mSerialPort != null) {
                Log.i(TAG, "SerialPort open success");
                this.inputStream = mSerialPort.getInputStream();
                this.outputStream = mSerialPort.getOutputStream();
            } else {
                Log.e(TAG, "SerialPort open fail");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws Exception {
        try {
            if (this.inputStream != null) {
                inputStream.close();
            }
            if (this.outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            if (mSerialPort != null) {
                mSerialPort.close();
                mSerialPort = null;
            }
        }catch (Exception e){
            Log.e(TAG,"串口对象关闭异常：" +e.toString());
        }
    }

    @Override
    public InputStream getInputStream() {
        return inputStream;
    }

    @Override
    public OutputStream getOutputStream() {
        return outputStream;
    }

    @Override
    public int getBaudRate() {
        return baudRate;
    }

    @Override
    public int getDataBits() {
        return dataBits;
    }

    @Override
    public int getStopBits() {
        return stopBits;
    }

    @Override
    public int getParity() {
        return parity;
    }

}
